import React, { useEffect, useState, useRef } from 'react'
import { Form, Button, Breadcrumb, DatePicker, Input, Select, Table, Pagination, Space, Modal, Dropdown, Drawer, Radio, message } from 'antd';
import { EyeOutlined, SettingOutlined, DownOutlined } from '@ant-design/icons';
import userApi from '../../../apis/user'
import roleApi from '../../../apis/role'
import deptApi from '../../../apis/deptApi'
import { Link } from 'react-router-dom';
import { downloadRoleInfoApi } from "../../../apis/dolw";
export default function user() {
  const [filterValue, setFilterValue] = useState()
  const [totalPage, setTotal] = useState(50)
  const [data, setData] = useState([])
  //获取角色信息
  const [roleList, setRoleList] = useState([])
  function getRole() {
    roleApi.getAllRoles({ pageSize: 10 }).then(res => {
      let roles = res.data.rows
      setRoleList(roles)
    })
  }
  //获取部门信息
  const [deptList, setDeptList] = useState([])
  function getDept() {
    deptApi.getDeptList().then(res => {
      setDeptList(res.data.rows.children)
    })
  }

  //修改的抽屉弹出
  const [form] = Form.useForm()
  const { Option } = Select;
  const [open, setOpen] = useState(false);
  const getUserId = useRef(0)
  const showDrawer = (e) => {
    if (e.userId) {
      e.roleId = Number(e.roleId)
      e.deptId = String(e.deptId)
      getUserId.current = e.userId
      form.setFieldsValue(e)
    } else {
      form.resetFields();
      form.setFieldsValue({
        password: '1234qwer'
      })
    }
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
    setTimeout(() => {
      getUserId.current = 0
    }, 10);

  };

  //修改/新增提交按钮
  const update = (values) => {
    if (getUserId.current != 0) {
      values = {
        ...values,
        userId: String(getUserId.current),
        deptId: String(values.deptId)
      }
      userApi.upDateUser(values).then(res => {
        console.log(res);
        message.success('修改成功')
        getUserId.current = 0
        getUserList()
        onClose()
      }).catch(err => {
        message.error('修改失败')
      })
    } else {
      values = {
        ...values,
        deptId: String(values.deptId)
      }
      values = `username=${values.username}&password=${values.password}&email=${values.email}&mobile=${values.mobile}&roleId=${values.roleId}&deptId=${values.deptId}&status=${values.status}&ssex=${values.ssex}`
      userApi.addUser(values).then(res => {
        console.log(res);
      })
    }
    console.log(values);
  }
  //表格:分页/筛选/排序
  const sortOrder = useRef({})
  const [filteredValue, setFilteredValue] = useState({})
  const onChange = (pageNumber, filters, sorter, extra) => {
    // console.log('params', pageNumber, filters, sorter, extra);
    console.log(sorter);
    if (filters) {
      console.log(filters);
      setFilteredValue(filters)
    }
    if (sorter) {
      sortOrder.current.order = sorter.order
      sortOrder.current.field = sorter.field
      getUserList({ pageNum: pageNumber, sortField: sortOrder.current.field, sortOrder: sortOrder.current.order })
    } else {
      getUserList({ pageNum: pageNumber })
    }
  };

  //表格头部，用户列表渲染
  const tableProps = {
    size: "Middle",
    rowSelection: "true"
  };

  const columns = [

    {
      title: '用户名',
      dataIndex: 'username',
      width: '200px',
      sorter: true,
      sortOrder: sortOrder.current.field == 'username' ? sortOrder.current.order : null
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      render: (text, record, index) => (
        <p>{record.ssex == 0 ? '男' : '' || record.ssex == 1 ? '女' : '' || record.ssex == 2 ? '保密' : ''}</p>
      ),
      filters: [
        {
          text: '男',
          value: 0,
        },
        {
          text: '女',
          value: 1,
        },
        {
          text: '保密',
          value: 2,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => record.ssex.indexOf(value) == 0,
      filteredValue: filteredValue.ssex || null
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptName',

    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text, record, index) => (
        <p className={record.status == 1 ? 'active' : 'unActive'}>{record.status == 1 ? '有效' : '锁定'}</p>
      ),
      filters: [
        {
          text: '锁定',
          value: 0,
        },
        {
          text: '有效',
          value: 1,
        },
      ],
      filterMultiple: false,
      onFilter: (value, record) => record.status.indexOf(value) == 0,
      filteredValue: filteredValue.status || null
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      sortOrder: sortOrder.current.field == 'createTime' ? sortOrder.current.order : null
    },
    {
      title: '操作',
      fixed: 'right',
      width: '150px',
      render: (text, record, index) => {
        return (<Space size="middle">
          <SettingOutlined style={{ color: '#00A1F5' }} onClick={() => showDrawer(record)} />
          <EyeOutlined style={{ color: '#00C292' }} onClick={() => showModal(record)} />
        </Space>
        )
      }
    },
  ];
  const [isModalOpen, setIsModalOpen] = useState(false);


  //详细信息模态框
  const [userInfo, setUserInfo] = useState({})
  const showModal = (e) => {
    setUserInfo(e)
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //查询/重置按钮
  const [searchForm] = Form.useForm()
  const { RangePicker } = DatePicker;
  const checked = useRef({})
  function goBack() {
    setFilteredValue({})
    searchForm.resetFields()
    sortOrder.current.order = null
    console.log(sortOrder.current);
    getUserList()
  }
  const onFinish = (values) => {
    console.log('Success:', values);
    if (values.data) {
      values.createTimeFrom = values.data[0].format('YYYY-MM-DD')
      values.createTimeTo = values.data[1].format('YYYY-MM-DD')
      console.log(values);
    }
    const checkedList = {
      createTimeFrom: values.createTimeFrom,
      createTimeTo: values.createTimeTo,
      username: values.username,
      deptId: values.deptId
    }
    console.log(checkedList);
    checked.current = checkedList
    getUserList(checked.current)
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const toExcel = (value) => {
    if (value === '导出excel') {
      downloadRoleInfoApi()
    }
  }
  //获取用户列表
  async function getUserList(params) {
    await userApi.getUser(params).then(res => {
      let all = res.data.total
      setTotal(all)
      let list = res.data.rows
      setData(list)
    })
  }
  useEffect(() => {
    getUserList()
    getRole()
    getDept()
  }, [])
  //选择&删除
  const [delUserId, setDelUserId] = useState([])
  const [delUserInfo, setDelUserInfo] = useState([])
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setDelUserId(selectedRowKeys)
      setDelUserInfo(selectedRows)
      // console.log(delUserId);
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 
      // 'selectedRows: ', selectedRows);
    }
  }
  function delUser() {
    delUserId.forEach(i => {
      userApi.delUser(i).then(res => {
        console.log(res);
        message.success('删除成功')
        getUserList()
      })
    })
  }
  const [isModalOpenDel, setIsModalOpenDel] = useState(false);
  const showModalDel = () => {
    if (delUserId.length > 0) {
      setIsModalOpenDel(true);
    } else {
      message.warning('请选择要删除的用户')
    }

  };
  const handleOkDel = () => {
    delUser()
    setIsModalOpenDel(false);
  };
  const handleCancelDel = () => {
    setIsModalOpenDel(false);
  };
  //页面渲染
  return (
    <div style={{ backgroundColor: 'white', width: '100%', padding: '20px 10px' }}>
      <Breadcrumb>
        <Breadcrumb.Item><Link to={'/layout/home'}>主页</Link></Breadcrumb.Item>
        <Breadcrumb.Item>
          系统管理
        </Breadcrumb.Item>
        <Breadcrumb.Item>用户管理</Breadcrumb.Item>
      </Breadcrumb>
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
        }}
        style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', width: '80%', marginTop: '20px' }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        form={searchForm}
      >
        <Form.Item
          label="用户名"
          name="username"
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="部门"
          name="deptId"
        >
          <Select placeholder="请选择部门" >
            {
              deptList.map(item => {
                return <Option key={item.key} value={item.id}>{item.title}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item
          label="创建时间"
          name="data"
        >
          <RangePicker />
        </Form.Item>
        <div style={{ display: 'flex' }}>
          <Form.Item
          >
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
          <Form.Item
            style={{ marginLeft: '10px' }}
          >
            <Button onClick={goBack} >
              重置
            </Button>
          </Form.Item>
        </div>
      </Form>
      <div style={{ padding: '0 50px' }}>
        <div>
          <Button onClick={showDrawer}>新增</Button>
          <Button style={{ margin: '0 10px' }} onClick={showModalDel}>删除</Button>
          <Select
            defaultValue="更多操作"
            style={{
              width: 120,
            }}
            onChange={toExcel}
          >
            <Select.Option value='密码重置'>重置密码</Select.Option>
            <Select.Option value='导出excel'>导出excel</Select.Option>

          </Select>
        </div>
        <div>
          <Table rowSelection={{
            ...rowSelection,
          }} columns={columns} pagination={false} dataSource={data} onChange={onChange} rowKey="userId" />
          <Pagination showQuickJumper total={totalPage} onChange={onChange} />
        </div>
      </div>
      { /* 用户详细信息 */}
      <Modal width={800} title="用户信息" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            <img style={{ width: '115px', height: '115px' }} src={'http://xawn.f3322.net:8002/distremote/static/avatar/' + userInfo.avatar} alt="" />
          </div>
          <div style={{ width: '300px' }}>
            <p>账户：{userInfo.username}</p>
            <p>角色：{userInfo.roleName}</p>
            <p>性别：{userInfo.ssex == '0' ? '男' : '' || userInfo.ssex == '1' ? '女' : '' || userInfo.ssex == '2' ? '保密' : ''}</p>
            <p>电话：{userInfo.mobile}</p>
            <p>邮箱：{userInfo.email}</p>
          </div>
          <div style={{ width: '300px' }}>
            <p>部门：{userInfo.deptName}</p>
            <p> 状态：<span className={userInfo.status == 1 ? 'active' : 'unActive'}>{userInfo.status == 1 ? '有效' : '锁定'}</span></p>
            <p>创建时间：{userInfo.createTime}</p>
            <p>最近登录：{userInfo.lastLoginTime}</p>
            <p>描述：{userInfo.description}</p>
          </div>
        </div>
      </Modal>
      {/* 修改右侧弹出窗 */}
      <Drawer
        title={getUserId.current == 0 ? '新增用户' : '修改用户'}
        destroyOnClose
        width={720}
        onClose={onClose}
        open={open}
        bodyStyle={{
          paddingBottom: 80,
        }}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 3,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={update}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              {
                required: true,
                message: 'Please choose the type',
              },
            ]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            style={{ display: `${getUserId.current != 0 ? 'none' : ''}` }}
          >
            <Input.Password title='默认初始密码1234qwer' disabled />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"

          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="mobile"
            label="手机号"
          >
            <Input placeholder="手机号" />
          </Form.Item>
          <Form.Item
            name="roleId"
            label="角色"
            rules={[
              {
                required: true,
                message: 'Please choose the type',
              },
            ]}
          >
            <Select
              mode='multiple'
            >
              {
                roleList.map(item => {
                  return <Option key={item.roleId} value={item.roleId}>{item.roleName}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item
            name="deptId"
            label="部门"
            rules={[
              {
                required: true,
                message: 'Please choose the type',
              },
            ]}
          >
            <Select>
              {
                deptList.map(item => {
                  return <Option key={item.key} value={item.id}>{item.title}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[
              {
                required: true,
                message: '请选择状态',
              },
            ]}
          >
            <Radio.Group>
              <Radio value="0">锁定</Radio>
              <Radio value="1">有效</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="ssex"
            label="性别"
            rules={[
              {
                required: true,
                message: '请选择性别',
              },
            ]}
          >
            <Radio.Group>
              <Radio value="0">男</Radio>
              <Radio value="1">女</Radio>
              <Radio value="2">保密</Radio>
            </Radio.Group>
          </Form.Item>

          <Button onClick={onClose}>
            取消
          </Button>
          <Button type='primary' htmlType="submit">
            提交
          </Button>
        </Form>
      </Drawer>
      {/* 确认删除模态框 */}
      <Modal title="确定删除？" open={isModalOpenDel} onOk={handleOkDel} onCancel={handleCancelDel} cancelText="取消" okText='确定'>
        <h2>确定删除以下用户吗？</h2>
        {
          delUserInfo.map(item => {
            return <p key={item.userId}>{item.username}</p>
          })
        }
      </Modal>
    </div>
  )
}
